package com.ideaaedi.springcloud.jd.commonspring.config;

import com.ideaaedi.commonspring.lock.DefaultRedisLockSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RedissonConfig
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.A
 */
@Slf4j
@Configuration
public class RedissonConfig {
    
    @Value("${spring.redis.host}")
    private String host;
    
    @Value("${spring.redis.port}")
    private String port;
    
    @Value("${spring.redis.password:}")
    private String password;
    
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String address = host + ":" + port;
        log.info("redis address -> {}", address);
        final SingleServerConfig singleServerConfig = config.useSingleServer()
                .setConnectionMinimumIdleSize(10)
                .setAddress("redis://" + address);
        if (StringUtils.isNotBlank(password)) {
            singleServerConfig.setPassword(password);
        }
        RedissonClient redissonClient = Redisson.create(config);
        // 给DefaultRedisLockSupport设置默认的redissonClient
        DefaultRedisLockSupport.initDefaultRedissonClient(redissonClient);
        return redissonClient;
    }
}
